using UnityEngine;

namespace NL.Advanced
{
    /// <summary>
    /// 跟随对象位置
    /// </summary>
    public class FollowObject : MonoBehaviour
    {
        /// <summary>
        /// 跟随的对象
        /// </summary>
        [Header("跟随的对象")]
        [SerializeField] private Transform _Followed;

        /// <summary>
        /// 是否朝向相机
        /// </summary>
        [Header("是否朝向相机")]
        [SerializeField] private bool _Billboard;

        /// <summary>
        /// 是否朝向相机（只转Y轴）
        /// </summary>
        [Header("是否朝向相机（只转Y轴）")]
        [SerializeField] private bool _BillboardY;

        [Header("相对跟随对象的偏移量")]
        [SerializeField] private Vector3 _Offset;

        private void Update()
        {
            UpdatePosition();
            UpdateBillboard();
        }

        private void UpdatePosition()
        {
            var followedPosition = _Followed.position;
            followedPosition += _Offset;
            transform.position = followedPosition;
        }

        private void UpdateBillboard()
        {
            var mainCamera = Camera.main;
            if (!mainCamera)
            {
                return;
            }

            if (_BillboardY)
            {
                var cameraForward = mainCamera.transform.forward;
                cameraForward.y = 0;
                var noYForward = Vector3.Normalize(cameraForward);
                transform.forward = noYForward;
            }
            else if (_Billboard)
            {
                transform.LookAt(mainCamera.transform);
            }
        }
    }
}